package com.itwanyan.m3u8loaderbypublic.core;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.itwanyan.m3u8loaderbypublic.dbdata.AbsDownloadHistoryDBHelper;
import com.itwanyan.m3u8loaderbypublic.dbdata.DefaultDownloadHistoryDBHelper;
import com.itwanyan.m3u8loaderbypublic.dbdata.LoadRecordBean;
import com.itwanyan.m3u8loaderbypublic.dbdata.TsFileLoadRecord;
import com.itwanyan.m3u8loaderbypublic.model.LocalFileRecordBean;
import com.itwanyan.m3u8loaderbypublic.model.M3U8;
import com.itwanyan.m3u8loaderbypublic.model.M3U8Ts;
import com.itwanyan.m3u8loaderbypublic.util.MUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2018/8/10.
 */

public  class PulicLoader {

    private static PulicLoader mFriday;

    private ExecutorService threadPool;
    private static final String TAG = "pause";

    private LinkedHashMap<String, Downloader> downloaderList;
    public static  final String  saveVieoPath  = Environment.getExternalStorageDirectory().getPath() + File.separator + "gkbb/video";



    private static AbsDownloadHistoryDBHelper downloadRecordDBHelper;//全局的数据库helper

//    保存url以及其对于的下载线程列表
    private LinkedHashMap<String, List<DownloadThread>> downloadThreadLinkedHashMap;


    private LinkedHashMap<String, List<DownloadThread>> getDownloadThreadLinkedHashMap() {
        return downloadThreadLinkedHashMap;
    }

    /**
     * 建议在Application中初始化
     *
     * @param downloadRecordDBHelper 数据库
     */
    public static void init(AbsDownloadHistoryDBHelper downloadRecordDBHelper) {


        PulicLoader.downloadRecordDBHelper = downloadRecordDBHelper;
    }


    public static AbsDownloadHistoryDBHelper getDownloadRecordDBHelper() {

        if (downloadRecordDBHelper == null) {
            downloadRecordDBHelper = new DefaultDownloadHistoryDBHelper();
        }

        return downloadRecordDBHelper;
    }


    private PulicLoader() {
        threadPool = Executors.newFixedThreadPool(20);
        downloadRecordDBHelper = new DefaultDownloadHistoryDBHelper();
        downloadThreadLinkedHashMap = new LinkedHashMap<>();
    }

    public static PulicLoader getInstance() {

        if (mFriday == null) {
            synchronized (PulicLoader.class) {
                if (mFriday == null) {
                    mFriday = new PulicLoader();
                }
            }
        }
        return mFriday;
    }
    /**
     * 添加下载器
     *
     * @param downloader
     * @return
     */
    private void addDownloader(Downloader downloader) {


        if (downloaderList == null) {

            downloaderList = new LinkedHashMap<>();
        }


        downloaderList.put(downloader.url, downloader);


    }


    /**
     * 暂停下载
     *
     * @param downloader
     * @return
     */
    public PulicLoader pauseDownloader(Downloader downloader) {


        if (downloader.getDownloadState() == DownloadState.START) {

            downloader.pause();
        }


        return this;
    }


    /**
     * 全部开始下载
     */
    public void startAllDownload() {

        if (downloaderList != null) {

            for (Map.Entry<String, Downloader> stringDownloaderEntry : downloaderList.entrySet()) {

                Downloader downloader = stringDownloaderEntry.getValue();
                if (downloader.getDownloadState() == DownloadState.PAUSE || downloader.getDownloadState() == DownloadState.FAIL) {
                    stringDownloaderEntry.getValue().download();
                    Log.e(TAG, "startAllDownload: "+ stringDownloaderEntry.getValue().url );

                }
            }

        }


    }

    /**
     * 获取下载列表
     *
     * @param callBack
     */
    public void getDownloadedList(DataCallBack<List<LoadRecordBean>> callBack) {


        if (callBack != null) {

            callBack.onData(PulicLoader.getDownloadRecordDBHelper().getFinishedLoadM3u8Files());
        }
    }
    /**
     * 获取下载列表
     *
     * @param callBack
     */
    public void getDownloadingList(DataCallBack<List<LoadRecordBean>> callBack) {


        if (callBack != null) {

            callBack.onData(PulicLoader.getDownloadRecordDBHelper().getUnFinishLoadM3u8Files());
        }
    }

    /**
     * 删除所有下载记录
     */
    public void forceDeleteAll() {

        if (downloaderList != null) {

            for (Map.Entry<String, Downloader> stringDownloaderEntry : downloaderList.entrySet()) {

                stringDownloaderEntry.getValue().deleteCacheFile();
            }

        }


    }

    /**
     * 删除所有下载记录
     */
    public void forceDelete(String videoId) {

        if (downloaderList != null) {

            Downloader downloader = downloaderList.get(videoId);
            downloader.deleteCacheFile();

        }


    }

    /**
     * 暂停所有下载
     */
    public void pauseAllDownloader() {

        if (downloaderList != null) {

            for (Map.Entry<String, Downloader> stringDownloaderEntry : downloaderList.entrySet()) {

                stringDownloaderEntry.getValue().pause();
                Log.e(TAG, "pauseAllDownloader: "+stringDownloaderEntry.getValue().url );

            }
        }

    }


    /**
     * 构建
     *
     * @param url 下载链接
     * @return
     */
    private Downloader withUrl(String url) {


        return new Downloader(url);

    }

    /**
     * 回调到主线程
     *
     * @param context
     * @return
     */
    public static Friday with(Context context) {
//        WeakReference<Context> contextWeakReference = new WeakReference<Context>(context);

        return new Friday();
    }
    /**
     * 回调到主线程
     *
     * @return
     */
    public static Friday with() {
//        WeakReference<Context> contextWeakReference = new WeakReference<Context>(MyApplication.getContext());

        return new Friday();
    }
    public static class Friday {


//        private WeakReference<Context> contextWeakReference;

        public Friday() {
//            this.contextWeakReference = contextWeakReference;
        }

        public Downloader withUrl(String videoId) {
            String urltest = "http://video5.gkbbapp.com/UpLoad/M3U8Media/2016/07/" + videoId + "/" + videoId + ".m3u8";
            if (PulicLoader.getInstance().downloaderList!=null){
                Downloader downloader = PulicLoader.getInstance().downloaderList.get(videoId);
                if (downloader!=null) return downloader;
            }
            return new Downloader(urltest);

        }
    }
    public static class Downloader implements IDownloader {

        private String url;//资源路径
        private String videoId;
        private String filePath;//存放路径
        private String fileName;//文件名
        private int threadCount = 3;//默认3个线程，最大只能4个
        private int pauseThreadCount = 0;//中断的线程数
        private int failThreadCount = 0;//失败的线程数

        private volatile int localFinishCount = 0;//下载的数量
        private volatile long debrisSize = 0L;//累计每个线程当前下载长度的总和
        private volatile long totalDownloadedSize = 0L;//每个线程完成后累加的下载长度总和，由于debrisSize有几率不能统计出进度为100%的情况，所以totalDownloadedSize用于显示进度为100%的情况



        private List<DownloadThread> downloadThreadList;//存放各个下载线程，用于暂停的情况


        private volatile int downloadState = DownloadState.PAUSE;//下载状态,默认为暂停

        //用于保存远端文件的长度及是否支持断点续传
//        private RemoteFile remoteFile;


//        //一个不可见的fragment，用于监听页面消失
//        private InvisibleFragment fragment;

        private long refreshTime = 200;//刷新频率
        private long fileLength = 0;//刷新频率

        //上一次刷新的时间
        private long lastRefreshTime = 0L;

        private volatile boolean uiVisible = true;//UI是否可见



        private float currentProgress = 0f;//当前进度


        private Map<String, String> requestPropertyMap = new HashMap<>();

        /**
         * 添加额外的请求头
         *
         * @param key
         * @param value
         * @return
         */
        public Downloader addExtraRequestProperty(String key, String value) {

            requestPropertyMap.put(key, value);
            return this;
        }

        /**
         * 添加额外的请求头
         *
         * @param map
         * @return
         */
        public Downloader addExtraRequestPropertyMap(Map<String, String> map) {


            requestPropertyMap.putAll(map);
            return this;
        }


        /**
         * @param url
         */
        public Downloader(String url) {

            this.url = url;
            if (TextUtils.isEmpty(url)) {


                throw new UrlException("url不能为空");

            }

            if (!(url.startsWith("https://") || url.startsWith("http://"))) {

                throw new UrlException("url不合法");
            }
            PulicLoader.getInstance().addDownloader(this);

        }


        /**
         * 是否允许应用界面不可见时仍然继续下载，context为service可忽略
         *
         * @param allow true 允许， false 界面不可见时暂停
         * @return
         */
        public Downloader allowBackgroundDownload(boolean allow) {

//            this.allowBackgroundDownload = allow;
            return this;
        }

        /**
         * 刷新频率
         *
         * @param refreshTime
         * @return
         */
        public Downloader refreshTime(long refreshTime) {

            if (refreshTime <= 100) {

                refreshTime = 100;
            }
            this.refreshTime = refreshTime;
            return this;
        }

        /**
         * 获取下载状态
         *
         * @return
         */
        public int getDownloadState() {
            return downloadState;
        }

        /**
         * 获取已下载的进度
         *
         * @return
         */
        public float getDownloadedProgress() {


            if (currentProgress > 0) {

                return currentProgress;
            }


            if (debrisSize == 0) {
                debrisSize = PulicLoader.downloadRecordDBHelper.getLoadM3u8FileLenth(videoId);
//                fileLength = remoteFile.getLength();

            } else {
//                fileLength = PulicLoader.downloadRecordDBHelper.getFileLengthRecord(url);

            }

            long downloadSize = debrisSize;
            float progress = 0;
            if (fileLength == 0) {
                progress = 0;
            } else {
                progress = downloadSize * 1.0f / fileLength;
            }
            if (progress == 1) {
                downloadState = DownloadState.FINISH;
            }


            return progress;
        }


        public void getDownloadedProgress(final DataCallBack<Float> callback) {


            PulicLoader.getInstance().threadPool.execute(new Runnable() {
                @Override
                public void run() {

                    Log.e("getDownloadedProgress", "Thread = " + Thread.currentThread().getName());
                    runThread(new ThreadCallBack() {
                        @Override
                        public void runOnUiThread() {
                            callback.onData(getDownloadedProgress());

                        }

                        @Override
                        public void runOnThread() {
                            callback.onData(getDownloadedProgress());

                        }
                    });
                }
            });


        }



        /**
         * 设置文件下载的目录
         *
         * @param videoId 文件下载的目录
         * @return
         */
        public Downloader filePath(String videoId) {
            this.filePath = MUtils.saveVieoPath + File.separator + videoId;
            File file = new File(filePath);
            if (!file.exists())file.mkdirs();//创建文件目录
            this.videoId = videoId;
            return this;
        }

        /**
         * 设置文件名，非必须
         *
         * @param fileName 文件名
         * @return
         */
        public Downloader fileName(String fileName) {

            this.fileName = fileName;
            return this;
        }

        /**
         * 设置下载线程数
         *
         * @param threadCount 线程数 最大
         * @return
         */
        public Downloader threadCount(int threadCount) {

            //设置有效值
            if (threadCount <= 0) {

                throw new ZeroThreadException();
            }

            if (threadCount >= 5) {
                threadCount = 5;
            }
            this.threadCount = threadCount;
            return this;
        }

        /**
         * 获取分段下载的线程数
         *
         * @return
         */
        public int getThreadCount() {

            return this.threadCount;
        }

        private class ZeroThreadException extends RuntimeException {

            public ZeroThreadException() {
                super("线程数量不能设置为0");
            }
        }

        private DownloadListener downloadListener;

        /**
         * 下载监听
         *
         * @param downloadListener
         * @return
         */
        public Downloader setDownloadListener(DownloadListener downloadListener) {

            this.downloadListener = downloadListener;

            return this;
        }


        private boolean isDownloadListenerExist() {


            return this.downloadListener != null;
        }


        @Override
        public void pause() {

            List<DownloadThread> downloadThreadList = PulicLoader.getInstance().getDownloadThreadLinkedHashMap().get(videoId);

            if (downloadThreadList != null && downloadThreadList.size() > 0) {

                for (int i = 0; i < downloadThreadList.size(); i++) {

                    DownloadThread downloadThread = downloadThreadList.get(i);
                    //停止写入数据
                    //中断该线程
                    downloadThread.interrupt();
                    Log.e(TAG, "pause: "+downloadThread.isPause() );
                }

                PulicLoader.getInstance().getDownloadThreadLinkedHashMap().remove(videoId);
            }


        }


        @Override
        public void delete() {
            pause();
            downloadRecordDBHelper.deleteLoadM3u8File(videoId);
        }


        @Override
        public boolean deleteCacheFile() {



            //不允许在下载过程中删除
            if (downloadState != DownloadState.START) {

                //同时删除文件
                String loadFileDir = saveVieoPath + videoId;
                File localFile = new File(loadFileDir);
                final boolean delete = localFile.delete();
                if (delete)
                    downloadRecordDBHelper.deleteLoadM3u8File(videoId);


                System.out.println("deleteCacheFile onPauseDone ");
                if (isDownloadListenerExist()) {
                    runThread(new ThreadCallBack() {
                        @Override
                        public void runOnUiThread() {

                            downloadListener.onDelete(delete);


                        }

                        @Override
                        public void runOnThread() {
                            downloadListener.onDelete(delete);

                        }
                    });

                }
                downloadState = DownloadState.DELETE;

                return delete;

            } else {
                downloadState = DownloadState.PAUSE;


                return false;
            }


        }


        @Override
        public void recovery() {


            download();

        }


        private void resetRefreshTime() {

            lastRefreshTime = 0L;
        }

        @Override
        public void download() {

            int loadState = PulicLoader.downloadRecordDBHelper.getM3u8LoadState(videoId);
            if (loadState == DownloadState.FINISH){
                Log.e("download", "--------已经下载啦--------");

                return;
            }
            if (downloadState == DownloadState.START) {
                Log.e("download", "--------正在下载中--------");

                return;
            }
            if (downloadState == DownloadState.START) {
                Log.e("download", "--------正在下载中--------");

                return;
            }

            Log.e("download", "--------开始下载--------");


            downloadState = DownloadState.START;
            //更新下载的状态
            PulicLoader.downloadRecordDBHelper.updateM3u8LoadState(videoId,DownloadState.START);
            if (isDownloadListenerExist()) {
                runThread(new ThreadCallBack() {
                    @Override
                    public void runOnUiThread() {
                        downloadListener.onStart();

                    }

                    @Override
                    public void runOnThread() {
                        downloadListener.onStart();

                    }
                });
            }

            debrisSize = PulicLoader.downloadRecordDBHelper.getLoadM3u8FileLenth(videoId);
            localFinishCount = PulicLoader.downloadRecordDBHelper.getLoadTsFilesCount(videoId);

            PulicLoader.getInstance().threadPool.execute(new Runnable() {
                @Override
                public void run() {

                    final M3U8 ret = new M3U8();
                    try {
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        if (conn.getResponseCode() == 200) {
                            String realUrl = conn.getURL().toString();
                            url = realUrl;
                            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                            String basepath = realUrl.substring(0, realUrl.lastIndexOf("/") + 1);
                            String m3u8Name = realUrl.substring(realUrl.lastIndexOf("/") + 1, realUrl.length());
                            String dirName = m3u8Name.substring(0, m3u8Name.lastIndexOf("."));
                            System.out.println("basepath==" + basepath);
//                            M3U8 ret = new M3U8();
                            ret.setVideoId(realUrl.substring(realUrl.lastIndexOf("/") ,realUrl.lastIndexOf(".")));
                            ret.setBasepath(basepath);

                            //临时下载目录
                            String tempDir = saveVieoPath + File.separator + dirName;
                            File file = new File(tempDir);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            tempDir += File.separator + m3u8Name;
                            File tempDirFile = new File(tempDir);
                            FileOutputStream outputStream = new FileOutputStream(tempDirFile);

                            String line;
                            float seconds = 0;
                            while ((line = reader.readLine()) != null) {
                                if (line.startsWith("#EXT-X-KEY")) {
                                    String[] lips = line.split(",");
                                    String uriStr = "URI=\"/storage/emulated/0/gkbb/enc.key\"";
                                    String lineTransStr = lips[0] + "," + uriStr + "," + lips[2]+"\n";
                                    outputStream.write(lineTransStr.getBytes());
                                } else {
                                    outputStream.write((line +"\n").getBytes());
                                }
                                if (line.startsWith("#")) {
                                    if (line.startsWith("#EXTINF:")) {
                                        line = line.substring(8);
                                        if (line.endsWith(",")) {
                                            line = line.substring(0, line.length() - 1);
                                        }
                                        seconds = Float.parseFloat(line);
                                    }
                                    continue;
                                }
//                                if (line.endsWith("m3u8")) {
//                                    return parseIndex(basepath + line);
//                                }
                                ret.addTs(new M3U8Ts(line, seconds));
                                seconds = 0;
                            }
                            reader.close();
                            outputStream.close();

                            ret.getTsList();
                        } else {
                            downloadListener.onFail();
                            PulicLoader.downloadRecordDBHelper.updateM3u8LoadState(videoId,DownloadState.FAIL);
                            return;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        downloadListener.onFail();
                        PulicLoader.downloadRecordDBHelper.updateM3u8LoadState(videoId,DownloadState.FAIL);
                    }

                    //避免重复获取
                    //开始分段进行下载
                    if (ret.getTsList().size() > 0) {
                        String loadTsUrl = ret.getBasepath() + ret.getTsList().get(0).getFile();
                        //计算要下载的文件的长度  伪长度
                        fileLength = RemoteFileUtil.getFileLength(loadTsUrl) * ret.getTsList().size();
                    }else {
                        downloadListener.onFail();
                        PulicLoader.downloadRecordDBHelper.updateM3u8LoadState(videoId,DownloadState.FAIL);
                        return;
                    }
                    downloadThreadList = new ArrayList<>();
                    //存数据
                    LoadRecordBean loadRecordBean = new LoadRecordBean(videoId,url,ret.getBasepath(),ret.getTsList().size(),0,fileLength,DownloadState.START);
                    PulicLoader.downloadRecordDBHelper.saveLoadM3u8File(loadRecordBean);
                    System.out.println("文件长度为fileLength = " + fileLength);
                    //分段大小
                    DownloadThread.ThreadDownloadListener childDownloadListener = new DownloadThread.ThreadDownloadListener() {
                        @Override
                        public void onDownload(long currentDownloadSize) {


                            synchronized (this) {

                                debrisSize += currentDownloadSize;

                                //已下载的长度（加上上次下载的长度）
                                final long downloadSize = debrisSize;
                                final float progress = downloadSize * 1.0f / fileLength;
                                currentProgress = progress;
//                                PulicLoader.downloadRecordDBHelper.updateM3u8FileLoadLength(videoId,downloadSize);
                                if (isDownloadListenerExist() && downloadState == DownloadState.START) {


                                    runThread(new ThreadCallBack() {
                                        @Override
                                        public void runOnUiThread() {
                                            //回调给UI线程
                                            //控制刷新频率
                                            if (System.currentTimeMillis() - lastRefreshTime > refreshTime) {

                                                if (uiVisible) {

                                                    downloadListener.onProgress(downloadSize, progress);
                                                }

                                                lastRefreshTime = System.currentTimeMillis();
                                            }

                                            if (progress == 1) {
                                                File file = new File(filePath + RemoteFileUtil.getRemoteFileName(url));

                                                if (file.exists()) {
                                                    downloadListener.onSuccess(file);
                                                    downloadState = DownloadState.FINISH;

                                                }
                                                resetRefreshTime();


                                            }
                                        }

                                        @Override
                                        public void runOnThread() {

                                            if (System.currentTimeMillis() - lastRefreshTime > refreshTime) {

                                                downloadListener.onProgress(downloadSize, progress);

                                                lastRefreshTime = System.currentTimeMillis();
                                            }

                                            if (progress == 1) {
                                                File file = new File(filePath);

                                                if (file.exists() && file.listFiles().length == (ret.getTsList().size() + 1)) {
                                                    downloadListener.onSuccess(file);
                                                    downloadState = DownloadState.FINISH;
                                                    resetRefreshTime();
                                                }


                                            }
                                        }
                                    });


                                }

                            }
                        }

                        @Override
                        public void onFinish(long total) {


                            synchronized (this) {
                                totalDownloadedSize += total;
                                localFinishCount++;
                                //下载完成的Ts文件+1  已经在DownloadThread中添加
//                                PulicLoader.downloadRecordDBHelper.adM3u8FileLoadTsCount(videoId);
                                //曾经中断的话，计算新的进度需要加上上一次已下载的文件长度
                                if (localFinishCount == ret.getTsList().size()) {
//                                if (fileLength == (totalDownloadedSize + lastDownloadedFileLength)) {

                                    currentProgress = 1.0f;

                                    PulicLoader.getInstance().getDownloadThreadLinkedHashMap().remove(videoId);
                                    PulicLoader.getDownloadRecordDBHelper().updateM3u8LoadState(videoId,DownloadState.FINISH);//更新下载完成的状态 同时删除TS文件

//                                    Downloader.downloadRecordDBHelper.clearDownloadRecordOfThisUrl(url);
                                    if (isDownloadListenerExist()) {

                                        runThread(new ThreadCallBack() {
                                            @Override
                                            public void runOnUiThread() {


                                                if (getDownloadState() != DownloadState.FINISH) {
                                                    if (uiVisible) {

                                                        downloadListener.onProgress(fileLength, 1.0f);

                                                        File file = new File(filePath);

                                                        if (file.exists() && file.listFiles().length == (ret.getTsList().size() + 1)) {

                                                            downloadListener.onSuccess(file);

                                                        }
                                                    }


                                                }
                                            }

                                            @Override
                                            public void runOnThread() {

                                                if (getDownloadState() != DownloadState.FINISH) {
                                                    downloadListener.onProgress(fileLength, 1.0f);

                                                    File file = new File(filePath);

                                                    if (file.exists() && file.listFiles().length == (ret.getTsList().size() + 1)) {

                                                        downloadListener.onSuccess(file);

                                                    }


                                                }
                                            }
                                        });
                                    }
                                    resetRefreshTime();
                                    downloadState = DownloadState.FINISH;
                                }
                            }
                        }


                        @Override
                        public void onFail() {
                            synchronized (this) {
                                if (downloadState != DownloadState.FAIL) {
                                    if (isDownloadListenerExist()) {
                                        runThread(new ThreadCallBack() {
                                            @Override
                                            public void runOnUiThread() {
                                                downloadListener.onFail();

                                            }

                                            @Override
                                            public void runOnThread() {
                                                downloadListener.onFail();

                                            }
                                        });
                                    }
                                    totalDownloadedSize = 0;
                                    downloadState = DownloadState.FAIL;
                                    PulicLoader.downloadRecordDBHelper.updateM3u8LoadState(videoId,DownloadState.FAIL);
                                }

                            }

                        }

                        @Override
                        public void onPause() {
                            synchronized (this) {

                                boolean allThreadPause = true;
                                if (downloadThreadList != null && downloadThreadList.size() > 0) {
                                    for (DownloadThread downloadThread : downloadThreadList) {
                                        //如果还有线程不是暂停状态
                                        if (downloadThread.getDownloadState() != DownloadState.PAUSE) {

                                            allThreadPause = false;

                                            break;

                                        }
                                    }
                                }

                                if (allThreadPause && (downloadState != DownloadState.PAUSE)) {

                                    Log.e("all thread ", "onPause ? " + allThreadPause);

                                    if (isDownloadListenerExist()) {


                                        runThread(new ThreadCallBack() {
                                            @Override
                                            public void runOnUiThread() {
                                                if (uiVisible) {

                                                    downloadListener.onPause();
                                                }

                                            }

                                            @Override
                                            public void runOnThread() {
                                                downloadListener.onPause();

                                            }
                                        });


                                    }
                                    downloadState = DownloadState.PAUSE;

                                    totalDownloadedSize = 0;

                                }


                            }
                        }


                    };

                    //创建下载线程
                    for (int i = 0; i < ret.getTsList().size(); i++) {
                        M3U8Ts m3U8Ts = ret.getTsList().get(i);
                        String loadUrl = ret.getBasepath()+m3U8Ts.getFile();
                        String basePath = ret.getBasepath();
                        String fileName = m3U8Ts.getFile();
                        Log.e(TAG, "loadTsFile: "+loadUrl );
                        Log.e(TAG, "loadTsFile:getBasepath= "+ret.getBasepath() );
                        Log.e(TAG, "loadTsFile:getFile= "+m3U8Ts.getFile() );
                        String fileDir = MUtils.saveVieoPath + "/" + ret.getVideoId()+"/";
                        boolean tsLoadState = PulicLoader.downloadRecordDBHelper.getTsFileLoadState(fileName);

                        if (!tsLoadState){

                            DownloadThread downloadThread  = new DownloadThread(videoId,loadUrl, fileDir, ret.getTsList().get(i).getFileName(),i, true, requestPropertyMap, childDownloadListener);
                            TsFileLoadRecord tsFileLoadRecord = new TsFileLoadRecord(videoId,fileName,basePath,0,i,false);
                            PulicLoader.downloadRecordDBHelper.saveLoadTsFile(tsFileLoadRecord);
                            //添加到线程池中
                            PulicLoader.getInstance().threadPool.execute(downloadThread);
                            //保存到列表进行维护
                            downloadThreadList.add(downloadThread);
                        }

                    }

                    //保存到map，绑定url和线程列表
                    PulicLoader.getInstance().getDownloadThreadLinkedHashMap().put(videoId, downloadThreadList);


                }
            });


        }

        private void runThread(final ThreadCallBack threadCallBack) {
            threadCallBack.runOnThread();

        }


    }
}
